package run.jingjing.websocket.endpoint;

import lombok.extern.slf4j.Slf4j;
import run.jingjing.websocket.model.LWsGroup;
import run.jingjing.websocket.model.LWsSession;
import run.jingjing.websocket.model.LWsTopic;
import run.jingjing.websocket.model.RunningTopic;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author: jingjing
 * @date: 2021/6/24
 * @description: global manager that endpoint and it reltated entity
 */
@Slf4j
public class EndpointManager extends ConcurrentHashMap<String, LWsGroup> {

    private static final Map<String, LWsGroup> container = new HashMap<>();

    public static final CopyOnWriteArraySet<RunningTopic> runningTopics = new CopyOnWriteArraySet<>();

    public static LWsGroup getGroup(String groupName) {
        LWsGroup group = container.get(groupName);
        if (group == null) {
            synchronized (EndpointManager.class){
                group = container.get(groupName);
                if (group == null) {
                    LWsGroup lWsGroup = new LWsGroup();
                    lWsGroup.setName(groupName);
                    group = lWsGroup;
                    container.put(groupName,group);
                }
            }
        }
        return group;
    }

    public static LWsTopic getTopic(String group, String topic) {
        LWsGroup lWsGroup = container.get(group);
        if (lWsGroup == null) return null;
        return lWsGroup.get(topic);
    }

    public static void removeRunningTopic(RunningTopic runningTopic){
        runningTopics.remove(runningTopic);
    }

    public static void onClose(LWsSession lWsSession) {
        if (lWsSession == null) {
            return;
        }
        if (lWsSession.getSession().isOpen()) {
            return;
        }
        LWsTopic topic = lWsSession.getTopic();
        topic.remove(lWsSession.getUserId());
    }
}
